package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //调用Mapper 递归查询分类信息

       List<CourseCategoryTreeDto>courseCategoryTreeDtos =  courseCategoryMapper.selectTreeNodes(id);
        //找到每个节点的子节点，最终封装成List<CourseCategoryTreeDto>

        //先将list转化为map，key就是节点的id value就是CourseCategoryTreeDto对象，目的就是为了方便从map获取节点
         Map<String ,CourseCategoryTreeDto>mapTemp = courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).collect(Collectors.toMap(CourseCategory::getId, value->value,(key1, key2)->key2));
         //定义一个最终返回结果
        ArrayList<CourseCategoryTreeDto> courseCategoryList = new ArrayList<>();
        //先从头遍历List<CourseCategoryTreeDto> ，一边遍历一边找子节点，放在父节点的childrenTreeNodes
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            //一级节点
            if (item.getParentid().equals(id)){
                courseCategoryList.add(item);
            }
            //找到节点的父节点
            CourseCategoryTreeDto courseCategoryTreeDtoParent = mapTemp.get(item.getParentid());


            if (courseCategoryTreeDtoParent!=null){ //说明该节点有父节点 ，有父节点则需要将该节点放在父节点的ChildrenTreeNodes属性中
                if (courseCategoryTreeDtoParent.getChildrenTreeNodes()==null){//如果父节点的ChildrenTreeNodes属性为空的话
                    courseCategoryTreeDtoParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                //将该节点放在父节点的ChildrenTreeNodes属性中
                courseCategoryTreeDtoParent.getChildrenTreeNodes().add(item);

            }

        });


        return courseCategoryList;
    }
}
